package com.server.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.common.base.PathManager;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.date.DateUtil;
import com.server.service.IOrgManagementService;
import com.server.web.DataVector;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;

@Controller
@RequestMapping("org")
public class OrgManagementController {

	@Autowired
	private IOrgManagementService orgManagementService;
	
	@RequestMapping("")
	public ModelAndView orgPage(){
		ModelAndView mv = new ModelAndView("org/orgList");
		mv.addObject("projectName",ProjectInfor.PLATFORM_NAME);
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		return mv;
	}
	@RequestMapping("list")
	public void list(HttpServletRequest request,
			HttpServletResponse response){ 
		String cardId = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		String level = SessionUtil.getStringAttri(request, SessionData.levelKey);
		RequestInput requestInput = new RequestInput(request);
		
		if (!level.equals("9")) {
			//查询用户所在公司
			String orgNo = orgManagementService.getOrg4User(cardId);
			String whereStr = requestInput.getWhereStr();
			if (whereStr.length() > 0) {
				whereStr += " and ";
			}
			whereStr += "OrgNo='"+orgNo+"'";
			requestInput.setWhereStr(whereStr);
		}
		
		DataVector<Map<String, Object>> listData = orgManagementService.getList(requestInput); 
		
		OutputUtil.returnString(response, JSONSerielizer.toJson(listData.getList(), null, null));
	}
	@RequestMapping("list4user")
	public void list4user(HttpServletRequest request,
			HttpServletResponse response){ 
		String cardId = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		String level = SessionUtil.getStringAttri(request, SessionData.levelKey);
		RequestInput requestInput = new RequestInput(request);
		
		List<Map<String, Object>> returnList = new ArrayList<>();
		
		if (!level.equals("9")) {
			//查询用户所在公司
			String orgNo = orgManagementService.getOrg4User(cardId);
			String whereStr = requestInput.getWhereStr();
			if (whereStr.length() > 0) {
				whereStr += " and ";
			}
			whereStr += "OrgNo='"+orgNo+"'";
			requestInput.setWhereStr(whereStr);
		}else{
			Map<String, Object> map = new HashMap<>();
			map.put("OrgNo", "all");
			map.put("OrgName", "全部");
			returnList.add(map);
		}
		
		DataVector<Map<String, Object>> listData = orgManagementService.getList(requestInput); 
		List<Map<String, Object>> list = listData.getList();
		
		returnList.addAll(list);
		
		OutputUtil.returnString(response, JSONSerielizer.toJson(returnList, null, null));
	}
	@RequestMapping("all")
	public void all(HttpServletRequest request,
			HttpServletResponse response){
		List<Map<String, Object>> list = orgManagementService.getAllOrg();
		OutputUtil.returnString(response, JSONSerielizer.toJson(list, null, null));
	}
	@RequestMapping("add")
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		ModelAndView mv = new ModelAndView("common/editFrame");
		mv.addObject("pagePath","pages/org/orgForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "new");
		mv.addObject("business", "org");
		mv.addObject("titleName", "新增合作企业");
		mv.addObject("userName", userName);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		return mv;
	}
	
	@RequestMapping("edit/{orgNo}")
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String orgNo) {
		String userName = SessionUtil.getStringAttri(request, SessionData.nameKey);
		ModelAndView mv = new ModelAndView("common/editFrame");
		mv.addObject("pagePath","pages/org/orgForm.jsp");
		mv.addObject("rootPath",ProjectInfor.ROOT_PATH);
		mv.addObject("action", "edit");
		mv.addObject("business", "org");
		mv.addObject("id", orgNo);
		mv.addObject("titleName", "修改合作企业");
		mv.addObject("userName", userName);
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		mv.addObject("fileServer",serverBuffer.toString());
		
		return mv;
	}
	
	@RequestMapping("form/{orgNo}")
	public void form(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String orgNo){
		Map<String, Object> formData = orgManagementService.getForm(orgNo);
		OutputUtil.returnString(response, JSONSerielizer.toJson(formData, null, null));
	}
	@RequestMapping("save/{action}")
	public void save(HttpServletRequest request,
			HttpServletResponse response,@PathVariable String action){
		String operator = SessionUtil.getStringAttri(request, SessionData.cardIdKey);
		String formData = request.getParameter("formData");
		Map<String, Object> inputMap = JSONSerielizer.toMap(formData);
		
		Boolean isSuccess = true;
		String info = null;
		if ("new".equals(action)) {
			isSuccess = orgManagementService.add(operator, inputMap);
			info = isSuccess ? "企业添加成功。" : "企业添加失败！";
		}else {
			isSuccess = orgManagementService.update(operator, inputMap);
			info = isSuccess ? "企业修改成功。" : "企业修改失败！";
		}
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("isSuccess", isSuccess);
		map.put("info", info);
		OutputUtil.returnString(response, JSONSerielizer.toJson(map, null, null));
	}
	
	@RequestMapping("delete/{orgNo}")
	public void delete(HttpServletRequest request,
			HttpServletResponse response, @PathVariable String orgNo){
		Map<String, Object> delete = orgManagementService.delete(orgNo);
		OutputUtil.returnString(response, JSONSerielizer.toJson(delete, null, null));
	}
	
	@RequestMapping("show")
	public ModelAndView show(HttpServletRequest request){
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
			.append(":").append(serverPort).append("/")
			.append(PathManager.FILE_MAPPING);
		
		ModelAndView mv = new ModelAndView("org/show");
		List<Map<String, Object>> list = orgManagementService.getList();
		Iterator<Map<String, Object>> iterator = list.iterator();
		while(iterator.hasNext()){
			Map<String, Object> next = iterator.next();
			Object timeObj = next.get("EmployTime");
			Object webObj = next.get("OrgWeb");
			Object imgObj = next.get("OrgImg");
			Object linkObj = next.get("EmployLink");
			Object contentObj = next.get("Content");
			if (timeObj != null) {
				next.put("EmployTime", DateUtil.getDateStr((Date)timeObj, "yyyy年MM月dd日"));
			}else {
				next.put("EmployTime", "无");
			}
			if (imgObj != null) {
				next.put("ImgUrl", serverBuffer.toString()+imgObj.toString());
			}
			if (webObj != null) {
				String webSite = webObj.toString();
				if (!webSite.startsWith("http://")) {
					webSite = "http://"+webSite;
				}
				next.put("OrgWeb", webSite);
			}
			if (linkObj != null) {
				String link = linkObj.toString();
				if (!link.startsWith("http://")) {
					link = "http://"+link;
				}
				next.put("EmployLinkUrl", link);
			}else {
				//next.put("EmployLink", "无");
			}
			if (contentObj != null) {
				String content = contentObj.toString();
				if (content.length() >= 19) {
					next.put("Content", content.substring(0, 19));
				}
			}else {
				next.put("Content", "无");
			}
		}
		mv.addObject("fileServer",serverBuffer.toString());
		mv.addObject("orgList", list);
		mv.addObject("orgCount", list.size());
		return mv;
	}
	@RequestMapping("detail/{orgNo}")
	public ModelAndView detail(HttpServletRequest request,@PathVariable String orgNo){
		
		StringBuffer serverBuffer = new StringBuffer();
		String serverName = request.getServerName();
		int serverPort = request.getServerPort();
		serverBuffer.append("http://").append(serverName)
		.append(":").append(serverPort).append("/")
		.append(PathManager.FILE_MAPPING);
		
		ModelAndView mv = new ModelAndView("org/detail");
		Map<String, Object> form = orgManagementService.getForm(orgNo);
		Object timeObj = form.get("EmployTime");
		Object webObj = form.get("OrgWeb");
		Object imgObj = form.get("OrgImg");
		Object linkObj = form.get("EmployLink");
		if (timeObj != null) {
			form.put("EmployTime", DateUtil.getDateStr((Date)timeObj, "yyyy年MM月dd日"));
		}else {
			form.put("EmployTime", "无");
		}
		if (imgObj != null) {
			form.put("ImgUrl", serverBuffer.toString()+imgObj.toString());
		}
		if (webObj != null) {
			String webSite = webObj.toString();
			if (!webSite.startsWith("http://")) {
				webSite = "http://"+webSite;
			}
			form.put("OrgWeb", webSite);
		}
		if (linkObj != null) {
			String link = linkObj.toString();
			if (!link.startsWith("http://")) {
				link = "http://"+link;
			}
			form.put("EmployLinkUrl", link);
		}else {
			//next.put("EmployLink", "无");
		}
		mv.addObject("fileServer",serverBuffer.toString());
		mv.addAllObjects(form);
		return mv;
	}
}
